//首页
<template>
	<view class="container">
		
		<view class="search-box">
			<navigator url="../search/search">
				<input class="uni-input" confirm-type="search" placeholder="请输入搜索内容" />
			</navigator>
		</view>
		
		<view class="tabs">
			<scroll-view id="tab-bar" class="scroll-h" :scroll-x="true" :show-scrollbar="false" :scroll-into-view="scrollInto">
				<view v-for="(tab,index) in tabBars" :key="tab.id" class="uni-tab-item" :id="tab.id" :data-current="index" @click="ontabtap">
					<text class="uni-tab-item-title" :class="tabIndex==index ? 'uni-tab-item-title-active' : ''">{{tab.name}}</text>
				</view>
			</scroll-view><!-- //图片滚动条 -->
			
			<!-- <view class="line-h"></view> -->
			<swiper :current="tabIndex" class="swiper-box" style="flex: 1;" :duration="300" @change="ontabchange">
				<swiper-item class="swiper-item" v-for="(tab,index1) in courseList" :key="index1">
					<scroll-view class="scroll-v list" enableBackToTop="true" scroll-y>
						<block v-if="tabIndex === 0">
							<swiper
								indicator-dots
								autoplay
								:interval="2000"
								:duration="500"
							>
							  <swiper-item v-for="(item, index) in recommendList" :key='index'>
								  <navigator :url="'../detail/detail?id' + item.id" class="recommend-link">
									  <image :src='item.imgUrl' mode="aspectFit"></image>
								  </navigator>
							  </swiper-item>
							</swiper> 
						</block>
					</block>
						<view v-for="(newsitem,index2) in tab" :key="newsitem.id">
							<media-item :options="newsitem" @close="close(index1,index2)" @click="goDetail(newsitem)"></media-item>
						</view>
						<!-- <view class="loading-more" v-if="tab.isLoading || tab.data.length > 4">
							<text class="loading-more-text">{{tab.loadingText}}</text>
						</view> -->
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>
	</view>
</template>
<script>
    import mediaItem from './news-item.nvue';
	import { getCourse } from '@/api';

    // 缓存每页最多
    const MAX_CACHE_DATA = 100;
    // 缓存页签数量
    const MAX_CACHE_PAGE = 3;

    const newsData = {
        data0: {
            "datetime": "40分钟前",
            "article_type": 0,
            "title": "uni-app行业峰会频频亮相，开发者反响热烈!",
            "source": "DCloud",
            "comment_count": 639
        },
        data1: {
            "datetime": "一天前",
            "article_type": 1,
            "title": "DCloud完成B2轮融资，uni-app震撼发布!",
            "image_url": "https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/shuijiao.jpg?imageView2/3/w/200/h/100/q/90",
            "source": "DCloud",
            "comment_count": 11395
        },
        data2: {
            "datetime": "一天前",
            "article_type": 2,
            "title": "中国技术界小奇迹：HBuilder开发者突破200万",
            "image_url": "https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/muwu.jpg?imageView2/3/w/200/h/100/q/90",
            "source": "DCloud",
            "comment_count": 11395
        },
        data3: {
            "article_type": 3,
            "image_list": [{
                "url": "https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/cbd.jpg?imageView2/3/w/200/h/100/q/90",
                "width": 563,
                "height": 316
            }, {
                "url": "https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/muwu.jpg?imageView2/3/w/200/h/100/q/90",
                "width": 641,
                "height": 360
            }, {
                "url": "https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/shuijiao.jpg?imageView2/3/w/200/h/100/q/90",
                "width": 640,
                "height": 360
            }],
            "datetime": "5分钟前",
            "title": "uni-app 支持使用 npm 安装第三方包，生态更趋丰富",
            "source": "DCloud",
            "comment_count": 11
        },
        data4: {
            "datetime": "2小时前",
            "article_type": 4,
            "title": "uni-app 支持原生小程序自定义组件，更开放、更自由",
            "image_url": "https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/cbd.jpg?imageView2/3/w/200/h/100/q/90",
            "source": "DCloud",
            "comment_count": 69
        }
    };

    export default {
        components: {
            mediaItem
        },
		onPullDownRefresh() {
			// 获取数据
			this.getCourseList().finally(() => uni.stopPullDownRefresh());
		},
        data() {
            return {
				// 销量最高的5个
				recommendList: [],
                // 课程数据
				courseList: [],
				
				newsList: [],
                cacheTab: [],
                tabIndex: 0, 
                tabBars: [{
                    name: '精选',
                    id: 'jinxuan'
                }, {
                    name: '考研',
                    id: 'kaoyan'
                }, {
                    name: '考编',
                    id: 'kaobian'
                }, {
                    name: '英语四六级',
                    id: 'yingyu'
                }, {
                    name: '中小学课程',
                    id: 'course'
                }],
                scrollInto: "",
                showTips: false,
                navigateFlag: false,
                pulling: false,
                refreshIcon: ""
            }
        },
        onLoad() {
            // setTimeout(()=>{
            //   this.tabBars.forEach((tabBar) => {
            //       this.newsList.push({
            //           data: [],
            //           isLoading: false,
            //           refreshText: "",
            //           loadingText: '加载更多...'
            //       });
            //   });
            //   this.getList(0);
            // },350)
			// 获取数据
			this.getCourseList();
        },
        methods: {
			// 获取课程数据
			//这里的getcourselist实际上是getCourse
			getCourseList() {
				uni.showLoading({
					title: '加载中...'
				})
				return getCourse({type: 1})
					.then(res => {
						const list = res.oData;
						// 组合数据
						this.composeCourseList(list);
						// 获取销量最高的5个
						this.getRecommendCourse(list);
					})
					.finally(() => {
						uni.hideLoading();
					})
			},
			// 组合课程数据
			composeCourseList(list) {
				let res = [list,[],[],[],[]];
				list.forEach(item => {
					if(item.tag === '考研') {
						res[1].push(item);
					} else if(item.tag === '考编') {
						res[2].push(item);
					} else if(item.tag === '英语四六级') {
						res[3].push(item);
					} else if(item.tag === '中小学课程') {
						res[4].push(item);
					}
				})
				// 排序
				res.forEach(list => {
					list.sort((a, b) => b.createTime - a.createTime);
				})
				this.courseList = res;
			},
			// 获取销量最高的5个
			getRecommendCourse(list) {
				//recommendList
				const res = [];
				const l = [...list];
				this.recommendList = l.sort((a, b) =>  b.saleNums - a.saleNums).slice(0, 5);
			},
            getList(index) {
                let activeTab = this.newsList[index];
                let list = [];
                for (let i = 1; i <= 10; i++) {
                    let item = Object.assign({}, newsData['data' + Math.floor(Math.random() * 5)]);
                    item.id = this.newGuid();
                    list.push(item);
                }
                activeTab.data = activeTab.data.concat(list);
            },
            goDetail(e) {
                if (this.navigateFlag) {
                    return;
                }
                this.navigateFlag = true;
                uni.navigateTo({
                    url: './detail/detail?title=' + e.title
                });
                setTimeout(() => {
                    this.navigateFlag = false;
                }, 200)
            },
            close(index1, index2) {
                uni.showModal({
                    content: '是否删除本条信息？',
                    success: (res) => {
                        if (res.confirm) {
                            this.newsList[index1].data.splice(index2, 1);
                        }
                    }
                })
            },
            loadMore(e) {
                setTimeout(() => {
                    this.getList(this.tabIndex);
                }, 500)
            },
            ontabtap(e) {
				// 改变tab
                let index = e.target.dataset.current || e.currentTarget.dataset.current;
				console.log(index);
                this.tabIndex = index;
            },
            ontabchange(e) {
				// 改变tab
				
                let index = e.target.current || e.detail.current;
                this.tabIndex = index;
            },
            switchTab(index) {
                if (this.courseList[index].data.length === 0) {
                    // this.getList(index);
					this.getCourseList(index);
                }

                if (this.tabIndex === index) {
                    return;
                }

                // 缓存 tabId
                if (this.courseList[this.tabIndex].data.length > MAX_CACHE_DATA) {
                    let isExist = this.cacheTab.indexOf(this.tabIndex);
                    if (isExist < 0) {
                        this.cacheTab.push(this.tabIndex);
                        //console.log("cache index:: " + this.tabIndex);
                    }
                }

                this.tabIndex = index;
                this.scrollInto = this.tabBars[index].id;

                // 释放 tabId
                if (this.cacheTab.length > MAX_CACHE_PAGE) {
                    let cacheIndex = this.cacheTab[0];
                    this.clearTabData(cacheIndex);
                    this.cacheTab.splice(0, 1);
                    //console.log("remove cache index:: " + cacheIndex);
                }
            },
            clearTabData(e) {
                this.newsList[e].data.length = 0;
                this.newsList[e].loadingText = "加载更多...";
            },
            refreshData() {},
            onrefresh(e) {
                var tab = this.newsList[this.tabIndex];
                if (!tab.refreshFlag) {
                    return;
                }
                tab.refreshing = true;
                tab.refreshText = "正在刷新...";

                setTimeout(() => {
                    this.refreshData();
                    this.pulling = true;
                    tab.refreshing = false;
					tab.refreshFlag = false;
                    tab.refreshText = "已刷新";
                    setTimeout(() => { // TODO fix ios和Android 动画时间相反问题
                        this.pulling = false;
                    }, 500);
                }, 2000);
            },
            onpullingdown(e) {
                var tab = this.newsList[this.tabIndex];
                if (tab.refreshing || this.pulling) {
                    return;
                }
                if (Math.abs(e.pullingDistance) > Math.abs(e.viewHeight)) {
                    tab.refreshFlag = true;
                    tab.refreshText = "释放立即刷新";
                } else {
                    tab.refreshFlag = false;
                    tab.refreshText = "下拉可以刷新";
                }
            },
            newGuid() {
                let s4 = function() {
                    return (65536 * (1 + Math.random()) | 0).toString(16).substring(1);
                }
                return (s4() + s4() + "-" + s4() + "-4" + s4().substr(0, 3) + "-" + s4() + "-" + s4() + s4() + s4()).toUpperCase();
            }
        }
    }
</script>

<style>
	.recommend-link {
		width: 100%;
		height: 100%;
	}
	
	.recommend-link > image {
		width: 100%;
		height: 100%;
	}
	
	.container {
		display: flex;
		flex-direction: column;
	}
	
	.search-box {
		display: flex;
		justify-content: center;
		padding-top: 5px;
		background-color: #fff;
	}
	
	.search-box navigator {
		display: flex;
		justify-content: center;
		width: 100%;
	}
	
	.search-box .uni-input {
		width: 80%;
		height: 20px;
		padding: 5px 10px;
		line-height:30px;
		background-color: #F0F0F0;
		border-radius: 20px;
		font-size: 14px;
		text-align: center;
	}
	
    /* #ifndef APP-PLUS */
    page {
        width: 100%;
        min-height: 100%;
        display: flex;
    }

    /* #endif */

    .tabs {
		display: flex;
        flex: 1;
        flex-direction: column;
        overflow: hidden;
        background-color: #f7f7f7;
        /* #ifdef MP-ALIPAY || MP-BAIDU */
        height: 100vh;
        /* #endif */
    }

    .scroll-h {
        width: 750rpx;
        height: 80rpx;
        flex-direction: row;
        /* #ifndef APP-PLUS */
        white-space: nowrap;
        /* #endif */
        /* flex-wrap: nowrap; */
        /* border-color: #cccccc;
		border-bottom-style: solid;
		border-bottom-width: 1px; */
        background-color: #fff;
    }

    .line-h {
        height: 1rpx;
        background-color: #fff;
    }

    .uni-tab-item {
        /* #ifndef APP-PLUS */
        display: inline-block;
        /* #endif */
        flex-wrap: nowrap;
        padding-left: 34rpx;
        padding-right: 34rpx;
    }

    .uni-tab-item-title {
        color: #555;
        font-size: 30rpx;
        height: 80rpx;
        line-height: 80rpx;
        flex-wrap: nowrap;
        /* #ifndef APP-PLUS */
        white-space: nowrap;
        /* #endif */
    }

    .uni-tab-item-title-active {
        color: #009afe;
    }

    .swiper-box {
        flex: 1;
    }

    .swiper-item {
		display: flex;
        flex: 1;
        flex-direction: row;
    }

    .scroll-v {
        flex: 1;
        /* #ifndef MP-ALIPAY */
        flex-direction: column;
        /* #endif */
        width: 750rpx;
    }

    .update-tips {
        position: absolute;
        left: 0;
        top: 41px;
        right: 0;
        padding-top: 5px;
        padding-bottom: 5px;
        background-color: #FDDD9B;
        align-items: center;
        justify-content: center;
        text-align: center;
    }

    .update-tips-text {
        font-size: 14px;
        color: #ffffff;
    }

    .refresh {
        width: 750rpx;
        height: 64px;
        justify-content: center;
    }

    .refresh-view {
        flex-direction: row;
        flex-wrap: nowrap;
        align-items: center;
        justify-content: center;
    }

	.refresh-icon {
		width: 30px;
		height: 30px;
		transition-duration: .5s;
		transition-property: transform;
		transform: rotate(0deg);
		transform-origin: 15px 15px;
	}

	.refresh-icon-active {
		transform: rotate(180deg);
	}

	.loading-icon {
		width: 20px;
		height: 20px;
		margin-right: 5px;
		color: #999999;
	}

    .loading-text {
        margin-left: 2px;
        font-size: 16px;
        color: #999999;
    }

    .loading-more {
        align-items: center;
        justify-content: center;
        padding-top: 10px;
        padding-bottom: 10px;
        text-align: center;
    }

    .loading-more-text {
        font-size: 28rpx;
        color: #999;
    }
</style>
